/*******************************************************************************
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package tr.edu.metu.is.mega.server.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import tr.edu.metu.is.mega.client.service.GwtUserCoursesViewService;
import tr.edu.metu.is.mega.common.dto.UserCoursesViewDTO;
import tr.edu.metu.is.mega.common.dto.UserDTO;
import tr.edu.metu.is.mega.common.dto.UserRole;
import tr.edu.metu.is.mega.server.business.UserCoursesViewManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GwtUserCoursesViewServiceImpl extends RemoteServiceServlet implements GwtUserCoursesViewService {

    private static final long serialVersionUID = -6116260334952230907L;

    private final UserCoursesViewManager manager;

    /**
     * Default constructor.
     */
    public GwtUserCoursesViewServiceImpl() {
        manager = new UserCoursesViewManager();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UserCoursesViewDTO> getCourses() {
        HttpServletRequest request = getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        UserDTO user = (UserDTO) session.getAttribute(GwtAuthenticationServiceImpl.USER_SESSION_STRING);
        if (user != null) {
            UserCoursesViewDTO dto = new UserCoursesViewDTO();
            if (user.getRole() != UserRole.ADMIN) {
                dto.setUserid(user.getPkid());
            } else {
                dto.setRole(user.getRole());
            }
            return manager.findByExample(dto);
        } else {
            return null;
        }
    }
}
